<template>
 <section>
    
    <div class="section-content clearfix">
        <el-col :span="24" class="toolbars" style="padding-bottom: 0px;">
                <el-form @submit.native.prevent :inline="true" >
                    <el-form-item v-if="userType==2">
                        <!-- <el-input v-model="filters.companyId" placeholder="组织" ></el-input> -->
                        <el-select v-model="filters.companyId" placeholder="组织" @change="getdevicetemplateuiList">
                            <!-- <el-option label="全部" value=" "></el-option> -->
                            <el-option v-for="item in firmlist" :label="item.name" :value="item.companyId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="filters.uiId" placeholder="UI模板" @change="getUsers">
                            <el-option v-for="item in querylist" :key="item.id" :label="item.name" :value="item.uiId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item >
                        <el-input v-model="filters.name" placeholder="名称" ></el-input>
                    </el-form-item>
                    <el-form-item >
                        <el-input v-model="filters.slaveSn" placeholder="从机号" ></el-input>
                    </el-form-item>
                    <el-form-item >
                        <el-input v-model="filters.register" placeholder="数据点" ></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button :type="buttonColor" @click="getUsers">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click.native.prevent="download()" :headers="fileList" :type="buttonColor" :loading="addLoading">下载模板</el-button>
                    </el-form-item>
                    <el-form-item >
                        <el-button :type="buttonColor" @click="handleAdd">新增</el-button>
                        <el-upload class="upload-demo" style="display: inline;" action="https://jsonplaceholder.typicode.com/posts/" ref="upload"
                            accept=".xls,.xlsx" :on-change="upload" :show-file-list="false" :auto-upload="false">
                            <el-button :type="buttonColor">批量导入</el-button>
                            
                             <div slot="tip" class="el-upload__tip">只能上传xls和pxlsx文件，且不超过5MB</div>
                        </el-upload>
                        
                    </el-form-item>
                    <!-- <el-form-item>
                        <el-button :type="buttonColor" @click="Registerset()">简码管理</el-button>
                    </el-form-item> -->
                </el-form>
            </el-col> 
            <!--列表-->
            <div style="font-size: 17px;font-weight: bold;margin-bottom: 10px;">
                <!-- 设备模板名称/UI模板名称 -->
                {{templateName}}
            </div>
            <el-table :data="query"  highlight-current-row v-loading="listLoading" :header-row-style="{backgroundColor: titleColor}" style="width: 100%;">
                <!-- <el-table-column type="selection"> -->
                <!-- </el-table-column> -->
                <el-table-column type="index" label="序号"  width="80" :index="indexMethod">
                </el-table-column>
                <el-table-column align="center" prop="name"  width="200" label="名称" >
                </el-table-column>
                <el-table-column align="center" prop="slaveSn" label="从机号" >
                </el-table-column>
                <el-table-column align="center" prop="register" label="数据点">
                </el-table-column>
                <el-table-column align="center" prop="cmdName" label="简码名称" >
                </el-table-column>
                <el-table-column align="center" label="首页显示" >
                    <template scope="scope">
                        <span v-show="scope.row.isHome == 0">否</span>
                        <span v-show="scope.row.isHome == 1">显示1-1</span>
                        <span v-show="scope.row.isHome == 2">显示2-2</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="remark" label="备注" >
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template scope="scope">
                            <i  @click="handleEdit(scope.$index, scope.row)" title="编辑" icon="el-icon-edit" circle class="pb-icon icon-edit"></i>
                            <i  @click="handleDel(scope.$index, scope.row)" icon="el-icon-delete" circle title="删除" class="pb-icon icon-delete"></i>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 工具条 -->
            <el-col :span="24" class="toolbar">
                <el-pagination style="float:right;" layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total">
                </el-pagination>
            </el-col>
    </div>

    <!--新增界面-->
        <el-dialog title="新增" v-show="addFormVisible" v-model="addFormVisible" :custom-class="dialogTitleColor" @close="addFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form @submit.native.prevent :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="addForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="从机号" prop="slaveSn">
                        <el-input v-model="addForm.slaveSn" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="数据点" prop="register">
                        <el-input v-model="addForm.register" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="简码" prop="cmdType">
                        <!-- <el-input v-model="addForm.cmdType" auto-complete="off"></el-input> -->
                        <el-select v-model="addForm.cmdType">
                            <!-- <el-option v-for="item in registerList" :label="item.name" :value="item.cmdType"></el-option> -->
                            <el-option v-for="item in registerList" :label="item.name" :value="item.cmdType"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="首页显示" prop="isHome">
                        <el-select v-model="addForm.isHome">
                            <el-option label='否' :value='0'></el-option>
                            <el-option label='显示1-1' :value='1'></el-option>
                            <el-option label='显示2-2' :value='2'></el-option>
                        </el-select>
                        <!-- <el-radio-group v-model="addForm.isHome">
                            <el-radio label="0">是</el-radio>
                            <el-radio label="1">否</el-radio>
                        </el-radio-group> -->
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input type="textarea" v-model="addForm.remark"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align: right;">
                    <el-button @click.native="addFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="addSubmit" :loading="addLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>

        <!--编辑界面-->
        <el-dialog title="编辑" v-show="editFormVisible" v-model="editFormVisible" :custom-class="dialogTitleColor" @close="editFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form @submit.native.prevent :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="editForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="从机号" prop="slaveSn">
                        <el-input v-model="editForm.slaveSn" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="数据点" prop="register">
                        <el-input v-model="editForm.register" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="简码" prop="cmdType">
                        <!-- <el-input disabled v-model="editForm.cmdType" auto-complete="off"></el-input> -->
                        <el-select v-model="editForm.cmdType">
                            <!-- <el-option v-for="item in registerList" :label="item.name" :value="item.cmdType"></el-option> -->
                            <el-option v-for="item in registerList" :label="item.name" :value="item.cmdType"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="首页显示" prop="isHome">
                        <el-select v-model="editForm.isHome">
                            <el-option label='否' :value='0'></el-option>
                            <el-option label='显示1-1' :value='1'></el-option>
                            <el-option label='显示2-2' :value='2'></el-option>
                        </el-select>
                        <!-- <el-radio-group v-model="editForm.isHome">
                            <el-radio :label='0'>是</el-radio>
                            <el-radio :label='1'>否</el-radio>
                        </el-radio-group> -->
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input type="textarea" v-model="editForm.remark"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align: right;">
                    <el-button @click.native="editFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="editSubmit" :loading="addLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
 </section>
</template>
<script>
import XLSX from 'xlsx'
import {
    devic_recipe_app_query,
    devic_recipe_app_put,
    devic_recipe_app_post,
    devic_recipe_app_get,
    devic_recipe_app_delete,
    register_query,
    user_querycompany,
    template_ui_query_cmd,
    template_ui_query,
    device_template_ui_company_query
}from "../../../api/api"
export default{
    data(){
        return{
            templateName:'',
            userType:'',
            page: 1,
            total: 0,
            fileList:[],
            listLoading:false,
            addFormVisible:false,
            addLoading:false,
            editFormVisible: false,
            query:[],
            registerList:[],
            querylist:[],
            filters:{
                name:'',
                slaveSn:'',
                register:'',
                companyId:'',
                uiId:''
            },
            addFormRules:{
                name: [{
                        required: true,
                        message: '请输入名字',
                        trigger: 'blur'
                    },  { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                slaveSn:[{
                        required: true,
                        message: '请输入从机号',
                        trigger: 'blur'
                }],
                register:[{
                        required: true,
                        message: '请输入数据点',
                        trigger: 'blur'
                }],
                cmdType:[{
                        required: true,
                        message: '请输入简码',
                        trigger: 'blur'
                }],
                isHome: [{
                    required: true,
                    message: "必填",
                    trigger: "blur"
                }],
            },
            editFormRules:{
                name: [{
                        required: true,
                        message: '请输入名字',
                        trigger: 'blur'
                    },  { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                slaveSn:[{
                        required: true,
                        message: '请输入从机号',
                        trigger: 'blur'
                }],
                register:[{
                        required: true,
                        message: '请输入数据点',
                        trigger: 'blur'
                }],
                cmdType:[{
                        required: true,
                        message: '请输入简码',
                        trigger: 'blur'
                }],
                isHome: [{
                    required: true,
                    message: "必填",
                    trigger: "blur"
                }],
            },
            //新增
            addForm:{
                isHome: 0,
                name:'',
                remark:'',
                slaveSn:'',
                register:'',
                cmdType:'',
                // deviceTemplateId: sessionStorage.getItem('deviceTemplateId')
                // remark:'',
            },
            //编辑
            editForm:{
                name:'',
                remark:'',
                slaveSn:'',
                register:'',
                cmdType:'',
                isHome: '',
                // remark:'',
            },
            firmlist:''
        }
    },
    computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
            dialogTitleColor(){
                return this.$store.state.dialogTitleColor
            },
        },
    methods:{
        Registerset(){
            this.$router.push('/template/registerset')
        },
        indexMethod(index) {
                let num = (this.page - 1) * 10 + index + 1;
                return num;
            },
        getUsers(){
            this.listLoading = true
            // if(this.filters.uiId){
            //     this.filters.uiId = this.filters.uiId.split("-")[0]
            // }
            console.log(this.filters.uiId)
            let para = { 
                pageNo:this.page,
                pageSize:10,
                name: this.filters.name,
                slaveSn: this.filters.slaveSn,
                register: this.filters.register,
                companyId: this.filters.companyId,
                // deviceTemplateId: sessionStorage.getItem('deviceTemplateId'),
                uiId: this.filters.uiId
            }
            devic_recipe_app_query(para).then((res) => {
                // console.log(res)
                this.query = res.data.list
                this.total = res.data.totalCount;
                this.page = res.data.pageNo;
                 this.listLoading = false
            })
            this.getregisterList()
        },
        //显示新增界面
            handleAdd: function () {
                console.log(this.addForm.isHome)
                this.addFormVisible = true;
                // this.addForm = {
                //     name: '',
                //     remark: ''
                // };
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({uiId:this.filters.uiId}, this.addForm);
                        console.log(para)
                        devic_recipe_app_post(para).then((res) => {
                                 this.begCode(res.code,res.message);
                                this.addLoading = false;
                                //NProgress.done();
                                
                        if (res.code == 0) {
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.getUsers();
                            }
                            });
                            
                        });
                    }
                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                console.log(row)
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
                // let para = {
                //     id:row.id
                // }
                // devic_recipe_app_get(para).then(res => {
                //     console.log(res)
                //     if(res.code == 0){
                //         this.editForm.name = res.data.name
                //         this.editForm.remark = res.data.remark
                //         this.editForm.slaveSn = res.data.slaveSn
                //         this.editForm.register = res.data.register
                //         this.editForm.cmdType = res.data.cmdType
                //         this.editForm.isHome = res.data.isHome
                //     } 
                // })
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let para = Object.assign({}, this.editForm);
                            // console.log(para)
                            devic_recipe_app_put(para).then((res) => {
                                 this.begCode(res.code,res.message);
                                
                                this.editLoading = false;
                                if (res.code == 0) {
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.getUsers();
                                }
                            });
                        });
                    }
                });
            },

            //删除
            handleDel: function(index, row){
                 this.$confirm('确认删除吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {
                        id: row.id
                    };
                    devic_recipe_app_delete(para).then((res) => {
                         this.begCode(res.code,res.message);
                        if (res.code == 0) {

                            this.listLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getUsers();

                        }
                    });
                }).catch(() => {

                });
            },
            handleCurrentChange(val){
                this.page = val;
                this.getUsers();
            },
            download() {
                // window.location.href = "https://" + location.host + "/公众号模板模板.xlsx"
                window.location.href = "https://" + location.host + "/公众号配方模板.xlsx"
            },
            upload(file, fileList) {
                console.log("file", file);
                console.log("fileList", fileList);
                let files = {
                    0: file.raw
                }
                this.readExcel1(files);
            },
            readExcel1(files) { //表格导入
                var that = this;
                console.log(files);
                if (files.length <= 0) { //如果没有文件名
                    return false;
                } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
                    this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
                    return false;
                }

                const fileReader = new FileReader();
                fileReader.onload = (ev) => {
                    console.log('ev=====================>',ev)
                    try {
                        const data = ev.target.result;
                        const workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        const wsname = workbook.SheetNames[0]; //取第一张表
                        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
                        console.log(ws);
                        this.addlist=ws;
                        for(let i in ws){
                            if(ws[i].首页显示 == '否'){
                                ws[i].首页显示 = 0
                            }else{
                                ws[i].首页显示 = 1
                            }
                            for(let k in this.registerList){
                                // console.log(ws[i].名称)
                                // console.log(this.registerList[k].name)
                                if(ws[i].名称 == this.registerList[k].name){
                                    ws[i].名称 = this.registerList[k].cmdType
                                }
                            }
                            let para = {
                                isHome: ws[i].首页显示,
                                name: ws[i].名称,
                                slaveSn: ws[i].从机号,
                                register: ws[i].数据点,
                                cmdType: ws[i].简码,
                                uiId:this.filters.uiId,
                            };
                            console.log(para)
                            devic_recipe_app_post(para).then((res) => {
                                
                                this.begCode(res.code,res.message);
                                //NProgress.done();
                                if(res.code==0){
                                this.addlist.splice(ws[i],1);
                                    this.$message({
                                    message: '新增成功',
                                    type: 'success'
                                });
                                this.getUsers();
                                }else{
                                    this.adderror=true
                                }
                                
                            });
                        }

                      
                        // that.peopleArr = [];//清空接收数据
                        // if(that.peopleArr.length == 1 && that.peopleArr[0].roleName == "" && that.peopleArr[0].enLine == ""){
                        //     that.peopleArr = [];
                        // }
                        //重写数据
                        try {

                        } catch (err) {
                            console.log(err)
                        }

                        this.$refs.upload.value = '';

                    } catch (e) {

                        return false;
                    }
                };
                fileReader.readAsBinaryString(files[0]);
            },
            getregisterList(){
                let para = {
                    pageSize: 1000,
                    uiId: this.filters.uiId,
                }
                // register_query(para).then(res => {
                //     if(res.code == 0){
                //         this.registerList = res.data.list
                //     }
                    
                // })
                template_ui_query_cmd(para).then(res => {
                    if(res.code == 0){
                        this.registerList = res.data.list
                    }
                    
                })
            },
            getdevicetemplateuiList(){
                sessionStorage.removeItem('devicetemplateuiId')
                sessionStorage.removeItem('deviceCompanyId')
                let para = {
                    pageNo: 1,
                    pageSize: 9999,
                    // type: 1,
                    companyId: this.filters.companyId,
                };
                device_template_ui_company_query(para).then((res) => { 
                // console.log(res)
                if(res.code == 0){
                    this.querylist = res.data.list
                    if(res.data.list != ''){
                        this.filters.uiId = this.querylist[0].uiId
                    }else{
                        this.filters.uiId = undefined
                    }
                    this.getregisterList()
                    this.getUsers() 
                }
            })
            }
    },
    mounted(){
        // if(sessionStorage.getItem('deviceTemplateName')){
        //     this.templateName = sessionStorage.getItem('deviceTemplateName')
        // }  
        let user = JSON.parse(sessionStorage.getItem('user'))
        this.userType = user.type
        if(sessionStorage.getItem('devicetemplateuiId')){
            this.filters.uiId = sessionStorage.getItem('devicetemplateuiId')
        }
        if(user.type != 2){
            this.filters.companyId = user.companyId
        }
        let para = {
            pageNo: 1,
            pageSize: 9999,
            type: 1
        };
        if(user.type == 2){
            user_querycompany(para).then(res => {
                this.begCode(res.code, res.message);
                if(res.code == 0){
                    this.firmlist = res.data.list;
                    if(sessionStorage.getItem("deviceCompanyId")){
                        this.filters.companyId = sessionStorage.getItem("deviceCompanyId")
                    }else{
                        this.filters.companyId = res.data.list[0].companyId
                    }
                    this.getdevicetemplateuiList()
                }
            });
        }else{
            this.getdevicetemplateuiList()
        }  
    },
    beforeDestroy(){
        sessionStorage.removeItem('devicetemplateuiId')
        sessionStorage.removeItem('deviceCompanyId')
    }
}
</script>

<style scoped>
.toolbars{
    padding: 10px 0 30px;
    background: #fff
}
</style>